package reports.directors;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;

import coreModel.HIT;
import coreModel.Item;
import coreModel.ProductContainer;
import coreModel.ProductGroup;
import coreModel.StorageUnit;
import coreModel.StorageUnitManager;
import reports.builders.IBuilder;

public class ExpiredItemReport implements IDirector, IVisitor {


	private static ArrayList<String> headers;
	private static SimpleDateFormat  dateFormater = new SimpleDateFormat("MM/dd/yyyy");
	Collection<Item> expiredItems;
	@Override
	public void build(IBuilder builder)
	{
		HIT.getInstance().getStorageUnitManager().preOrderAccept(this);

		builder.addTitle("Expired Item Reports");
		builder.startTable(6);
		builder.addTableHeader(headers);
		for(Item item : expiredItems)
		{
			builder.addRow(buildArrayofItem(item));
		}
		builder.endTable();
		builder.saveToFile();
	}

	private Collection<String> buildArrayofItem(Item item)
	{
		//create array
		ArrayList<String> tmp = new ArrayList<String>();
		// add description
		tmp.add(item.getProduct().getDescription());
		ProductContainer container=HIT.getInstance().getStorageUnitManager().
		getParentStorageUnit(item.getParentContainer());

		//add SU
		tmp.add(container.getName());
		// if in a product group
		if(!container.getName().equals(item.getParentContainer().getName()))
		{
			//add pg
			tmp.add(item.getParentContainer().getName());
		}
		else
		{
			tmp.add("");
		}

		tmp.add(dateFormater.format(item.getEntryDate()));
		tmp.add(calculateExpirationDate(item));
		tmp.add(item.getBarcode().toString());

		return tmp;
	}

	private String calculateExpirationDate(Item item)
	{
		Date entryDate = item.getEntryDate();
		GregorianCalendar calendar = new GregorianCalendar();
		calendar.setTime(entryDate);
		calendar.add(GregorianCalendar.MONTH,item.getProduct().getShelfLife());
		return dateFormater.format(calendar.getTime());
	}

	public ExpiredItemReport()
	{
		expiredItems= new ArrayList<Item>();

		//set up headers
		headers=new ArrayList<String>();
		headers.add("Description");
		headers.add("Storage Unit");
		headers.add("Product Group");
		headers.add("Entry Date");
		headers.add("Expire Date");
		headers.add("Item Barcode");

	}

	@Override
	public void visit(ProductGroup productGroup)
	{
		Collection<Item> allItems = HIT.getInstance().getItemManager().
		getAllItemsOfContainer(productGroup);
		
		for(Item item: allItems)
		{
			if(item.isExpired())
			{
				expiredItems.add(item);
			}
		}

	}

	@Override
	public void visit(StorageUnit storageUnit)
	{
		Collection<Item> allItems = HIT.getInstance().getItemManager().
		getAllItemsOfContainer(storageUnit);

		for(Item item: allItems)
		{
			if(item.isExpired())
			{
				expiredItems.add(item);
			}
		}

	}

	@Override
	public void visit(StorageUnitManager suManager)
	{
		// do nothing

	}

}
